package top.i51213.fastaction.action.pdf;

import android.content.Context;
import android.net.Uri;
import android.view.View;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import top.i51213.fastaction.R;
import top.i51213.fastaction.action.BaseActonComponent;
import top.i51213.fastaction.action.Data;
import top.i51213.fastaction.action.DataType;
import top.i51213.fastaction.action.IntentType;
import top.i51213.fastaction.uri.MimeType;
import top.i51213.fastaction.uri.UriReader;
import top.i51213.fastaction.uri.UriWriter;
import top.i51213.fastaction.util.IOUtil;

public class ToPdfActonComponent extends BaseActonComponent {
    public ToPdfActonComponent(Context context) {
        super(context);
    }

    @Override
    public int getImageResId() {
        return R.mipmap.pdf;
    }

    @Override
    public String getTitle() {
        return "转Pdf";
    }

    @Override
    public String getInfo() {
        return "支持Jpeg、Png、Webp、Pdf\n(对可读Pdf文件去除保护密码)";
    }

    @Override
    public View getEditView() {
        return null;
    }

    @Override
    public void editViewDismissListener() {

    }

    @Override
    protected Data makeOutputData() {
        Data pdfData = new Data(DataType.PdfFile);
        if (getInputData().getDataType() == DataType.IMAGE) {
            pdfData.addData(image2Pdf(getInputData()));
        } else if (getInputData().getDataType() == DataType.PdfFile) {
            pdfData.addData(pdfs2Pdf(getInputData()));
        }
        return pdfData;
    }

    @Override
    public IntentType getCurrentIntentType() {
        return IntentType.Pdf;
    }

    @Override
    public DataType getOutputDataType() {
        return DataType.PdfFile;
    }

    private Data image2Pdf(Data inputData) {
        Data pdfData = new Data(DataType.PdfFile);
        try {
            List<Uri> list = inputData.getUris();
            String fileName = list.size() == 1 ? new UriReader(getContext(), list.get(0)).getDisPlayName("") : IOUtil.getLongTimeString();
            String displayName = IOUtil.getFileNameNoExt(fileName) + ".pdf";
            UriWriter uriWriter = new UriWriter(getContext(), displayName, MimeType.Others.Any, true);

            Document document = new Document(new RectangleReadOnly(21 * 72 / 2.54f, 29.7f * 72 / 2.54f));
            document.setMargins(0,0,0,0);
            Rectangle rectangle = document.getPageSize();
            OutputStream fos = new BufferedOutputStream(uriWriter.openOutputStream());
            PdfWriter writer = PdfWriter.getInstance(document, fos);
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
            document.open();
            //System.out.println(document.topMargin()+" "+document.bottomMargin()+" "+document.leftMargin()+" "+document.rightMargin());
            for (Uri uri : inputData.getUris()) {
                UriReader uriReader = new UriReader(getContext(), uri);
                InputStream inputStream = uriReader.openAutoCloseInputStream();
                byte[] data = PdfUtil.readImageData(inputStream);
                inputStream.close();
                Image image = Image.getInstance(data);

                //System.out.println(uri);
                float dw = rectangle.getWidth() - document.leftMargin() - document.rightMargin();
                float dh = rectangle.getHeight() - document.topMargin() - document.bottomMargin();

                float iw = image.getScaledWidth();
                float ih = image.getScaledHeight();
                //System.out.println("w:" + image.getScaledWidth() + " h:" + image.getScaledHeight());
                if (iw != ih) {
                    if ((dw > dh) ^ (iw > ih)) {
                        //image.setRotation(90);
                        image.setRotationDegrees(90);
                    }
                }
                //System.out.println("w:" + image.getScaledWidth() + " h:" + image.getScaledHeight());
                float nw, nh;
                iw = image.getScaledWidth();
                ih = image.getScaledHeight();
                if (ih * dw > dh * iw) {//图片过高
                    nw = iw * dh / ih;//乘以放缩比
                    nh = dh;
                } else {
                    nw = dw;
                    nh = ih * dw / iw;
                }
                PdfUtil.scaleToFit(image, nw, nh);
                float left =  document.leftMargin();
                float bottom = document.bottomMargin();
                image.setAbsolutePosition(left + (dw - nw) / 2, bottom + (dh - nh) / 2);
                document.newPage();
                document.add(image);
            }
            document.close();
            pdfData.addData(DataType.PdfFile, uriWriter.getUri());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfData;
    }

    private Data pdfs2Pdf(Data inputData) {
        Data pdfData = new Data(DataType.PdfFile);
        Document document = new Document();
        try {
            List<Uri> list = inputData.getUris();
            String fileName = list.size() == 1 ? new UriReader(getContext(), list.get(0)).getDisPlayName("") : IOUtil.getLongTimeString();
            String displayName = IOUtil.getFileNameNoExt(fileName) + ".pdf";
            UriWriter uriWriter = new UriWriter(getContext(), displayName, MimeType.Others.Any, true);

            PdfCopy pdfCopy = new PdfCopy(document, new BufferedOutputStream(uriWriter.openOutputStream()));
            pdfCopy.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
            document.open();

            for (int i = 0; i < list.size(); i++) {
                Uri uri = list.get(i);
                UriReader uriReader = new UriReader(getContext(), uri);
                MyPdfReader pdfReader = new MyPdfReader(uriReader.openInputStream());

                if ((!pdfReader.isOpenedWithFullPermissions()) && pdfReader.isEncrypted()) {
                    pdfReader.decryptOnPurpose();
                }
                pdfCopy.addDocument(pdfReader);
                pdfReader.close();
            }
            pdfCopy.close();
            document.close();
            pdfData.addData(DataType.PdfFile, uriWriter.getUri());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfData;
    }
}
